<template>
  <el-dialog title="股票详情" :visible.sync="dialogVisible" width="1200px" class="detailsDialog">
    <div class="flex-between flex-v-center" style="background-color: #202127">
      <el-select v-model="baseApi" placeholder="请选择" @change="getList">
        <el-option
          v-for="item in baseApis"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        ></el-option>
      </el-select>
      <ul class="mainBody_tab_tilte clearfix" style="color: #fff">
        <li @click="output">
          <img src="../assets/image/mainCon_icon2.png" />
          <span>导出数据</span>
        </li>
        <li @click="saveTableImg">
          <img src="../assets/image/mainCon_icon4.png" />
          <span>保存为图片</span>
        </li>
      </ul>
    </div>
    <div class="table-l emptyLeft" ref="tableWrapper">
          
      <el-table
        id="mydialogtable"
        :data="tableData"
        height="700"
        style="width: 100%; background-color: #202127"
      >
        <el-table-column type="index" width="55"></el-table-column>
        <template v-for="item in tableColumn">
          <el-table-column
            :key="item.key"
            :prop="item.prop"
            :label="item.label"
            :show-overflow-tooltip="true"
            :width="item.width || 150"
            sortable
            align="center"
          >
          </el-table-column>
        </template>
      </el-table>
    </div>
  </el-dialog>
</template>

<script>
import XLSX from "xlsx";
import FileSaver from "file-saver";
import html2canvas from "html2canvas";
import listPageConfig from "./components/macro/listPageConfig";
import _ from 'lodash';

export default {
  data() {
    return {
            baseApis: listPageConfig,

      baseApi:'',
      dialogVisible: false,
      tableData: [],
      tableColumn: [],
      defaultCheckedKeysTime: [],
      defaultCheckedKeysData: [],
      defaultCheckedKeysRegion: [],
      defaultCheckedKeysHsp: [],
      getIndex: [],
      sourceDataChecked: [], // 接口返回的默认选中的指标
      page: 1,
      limit: 20,
      total: 0,
      currentCode:''
    };
  },
  computed: {
    tableName() {
      if (this.$route.query.tablename.indexOf("season") != -1)
        //前4/8/12季度
        this.timeFilterSelectArr = [
          {
            value: "全部",
            label: "全部",
          },
          {
            value: 4,
            label: "前4季度",
          },
          {
            value: 8,
            label: "前8季度",
          },
          {
            value: 12,
            label: "前12季度",
          },
        ];
      else if (this.$route.query.tablename.indexOf("month") != -1)
        //前4/8/12季度
        this.timeFilterSelectArr = [
          {
            value: "全部",
            label: "全部",
          },
          {
            value: 12,
            label: "前12月",
          },
          {
            value: 24,
            label: "前24月",
          },
          {
            value: 36,
            label: "前36月",
          },
        ];

      return this.$route.query.tablename || "area_province_year";
    },
    tableColumn() {
      console.log(
        this.baseApis.find((item) => {
          return item.key === this.baseApi;
        }).thead
      );
      return this.baseApis.find((item) => {
        return item.key === this.baseApi;
      }).thead;
    },
    bodyData() {
      let item = this.baseApis.find((item) => {
        return item.key === this.baseApi;
      });

      return {
        url: `5600/` + item.value,
        method: "post",
        params: {
          page: this.page,
          limit: this.limit,
          code: this.currentCode,
          CODES: this.currentCode,
          INF00008S: this.defaultCheckedKeysData.join(","),
          INF00010S: this.defaultCheckedKeysRegion.join(","),
          INF00024S: this.defaultCheckedKeysHsp.join(","),
          TIMES: this.defaultCheckedKeysTime.join(","),
        },
      };
    },
  },
    watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    filterTextRegion(val) {
      this.$refs.treeRegion.filter(val);
    },
    filterTextTime(val) {
      this.$refs.treeTime.filter(val);
    },
    filterTextHsplate(val) {
      this.$refs.dataHsplate.filter(val);
    },
    defaultCheckedKeysData(val) {
      this.getIndex = val;
      Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
          if (this[i] == val) return i;
        }
        return -1;
      };
      Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
          this.splice(index, 1);
        }
      };
      var emp = this.getIndex;
      emp.remove("全选");
    },
    defaultCheckedKeysRegion(val) {
      this.getRegion = val;
      Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
          if (this[i] == val) return i;
        }
        return -1;
      };
      Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
          this.splice(index, 1);
        }
      };
      var emp = this.getRegion;
      emp.remove("全选");
    },
    defaultCheckedKeysTime(val) {
      this.getTime = val;
      Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
          if (this[i] == val) return i;
        }
        return -1;
      };
      Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
          this.splice(index, 1);
        }
      };
      var emp = this.getTime;
      emp.remove("全选");
    },
    defaultCheckedKeysHsp(val) {
      this.getHsp = val;
      Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
          if (this[i] == val) return i;
        }
        return -1;
      };
      Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
          this.splice(index, 1);
        }
      };
      var emp = this.getHsp;
      emp.remove("全选");
    },
  },
  methods: {
    async firstInit() {
      var that = this;
      var params = {};
      let resIndex = await this.$axios.request({
        url: "5600/hscomclass/gethsmenu",
        method: "get",
        params: params,
      });
      if (resIndex) {
        let data1 = resIndex.data.data;
        let defaultCheckedKeysData = [];
        data1.forEach((item) => {
          if (item.isShow) {
            defaultCheckedKeysData.push(item.name);
          }
        });
        this.defaultCheckedKeysData = defaultCheckedKeysData;
        this.sourceDataChecked = _.cloneDeep(defaultCheckedKeysData);
        var data = that.getNavData(_.cloneDeep(data1));
        this.data = [
          {
            id: "all",
            label: "全选",
            children: data,
          },
        ];
      }

      let dataTime1 = await this.$axios.request({
        url: "5600/hscomclass/gethsmodel",
        method: "get",
        params: params,
      });
      if (dataTime1) {
        let data = dataTime1.data.datas;
        data.sort(function (a, b) {
          return b - a;
        });
        that.timeSource = data;
        if (dataTime1.data) {
          let timeArr = [];
          for (let e of data) {
            timeArr.push({
              id: e,
              label: e,
            });
          }
          this.dataTime = [
            {
              id: "all",
              label: "全选",
              children: timeArr,
            },
          ];
        }
      }

      let dataRegion1 = await this.$axios.request({
        url: "5600/hscomclass/gethsregion",
        method: "get",
        params: params,
      });
      if (dataRegion1) {
        let dataRegionArr = [];
        for (let e of dataRegion1.data.datas) {
          dataRegionArr.push({
            id: e,
            label: e,
          });
        }
        this.dataRegion = [
          {
            id: "all",
            label: "全选",
            children: dataRegionArr,
          },
        ];
      }

      let gethsplate = await this.$axios.request({
        url: "5600/hscomclass/gethsplate",
        method: "get",
        params: params,
      });
      if (gethsplate) {
        let gethsplateArr = [];
        for (let e of gethsplate.data.datas) {
          gethsplateArr.push({
            id: e,
            label: e,
          });
        }
        this.dataHsplate = [
          {
            id: "all",
            label: "全选",
            children: gethsplateArr,
          },
        ];
      }

      this.getList();
    },
    async getList() {

     this.tableColumn= this.baseApis.find((item) => {
        return item.key === this.baseApi;
      }).thead;

      if (this.baseApi == "1") {
        ///5600/hscominfo/findByCode/{code}
        this.$axios
          .request({
            url: `5600/hscominfo/findByCode/${this.currentCode}`,
            method: "get",
          })
          .then(({ data }) => {
            let arr = [];
            arr.push(data.info);
            this.$refs.detailsDialog.settableColumnandtableData(
              this.tableColumn,
              arr,
              this.defaultCheckedKeysTime,
              this.settableColumnandtableData,
              this.defaultCheckedKeysHsp
            );
          });
      } else {

        let res = await this.$axios.request(this.bodyData);
        if (String(res.data.code) === "1") {
          // 失败
          this.$message.error(res.data.resp_msg);
          return;
        }
        let datas = Object.assign([], _.get(res, "data.data", []));
        this.sourceData = _.cloneDeep(datas);
        this.tableData = Object.assign([], datas);
        this.total = _.get(res, "data.count", 0);
        if (this.baseApi === "1") {
          this.baseCodes = datas
            .map((item) => {
              return item.code;
            })
            .join(",");
        }
      }
    },
    saveTableImg() {
      html2canvas(this.$refs.tableWrapper).then((canvas) => {
        let dataURL = canvas.toDataURL("image/png");
        let link = document.createElement("a");
        link.href = canvas.toDataURL(); //下载链接
        link.setAttribute("download", $(".excelName").html());
        link.style.display = "none"; //a标签隐藏
        document.body.appendChild(link);
        link.click();
      });
    },
    settableColumnandtableData(
      tableColumn,
      tableData,
      defaultCheckedKeysTime,
      defaultCheckedKeysRegion,
      defaultCheckedKeysHsp,currentCode,baseApi
    ) {
      this.baseApi=baseApi;
       this.baseApis=listPageConfig;
      this.tableColumn = tableColumn;
      this.defaultCheckedKeysTime = defaultCheckedKeysTime;
      this.tableData = tableData;
      this.dialogVisible = true;
      this.defaultCheckedKeysRegion = defaultCheckedKeysRegion || [];
      this.defaultCheckedKeysHsp = defaultCheckedKeysHsp;
      this.currentCode=currentCode
      this.firstInit();
    },
    output() {
      var excelName = $(".excelName").html();
      /* generate workbook object from table */
      var tdLength = $("#mydialogtable")
        .children(".el-table__fixed-body-wrapper")
        .find("tbody")
        .find("tr:first-child td").length;
      var addFooterHtml =
        '<tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"><td></td><td>数据来源：数据圈</td></tr><tr class="tableNone"><td></td><td>电话：010-64788139</td></tr><tr class="tableNone"><td></td><td>E-mail：joy@shujuquan.com</td></tr>';
      $("#mydialogtable")
        .find(".el-table__fixed-body-wrapper")
        .find("tbody")
        .append(addFooterHtml);
      var wb;

      wb = XLSX.utils.table_to_book(document.querySelector("#mydialogtable"));

      //var wb = XLSX.utils.table_to_book(document.querySelector("#mydialogtable")); //mydialogtable为表格的id名
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      let date = new Date();
      date = `${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`;
      console.log(date);
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          `` + excelName + `${date}.xlsx`
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
  },
};
</script>

<style scoped>
  
/deep/ .el-dialog{
  background: #202127;
  margin-top: 8vh !important;
}
/deep/ .el-dialog__close,/deep/ .el-dialog__title{
  color: #fff;
}
/deep/.detailsDialog .el-table__body-wrapper{
  height: 560px !important;
}
/deep/ .el-table th.gutter{
display: table-cell!important;
}
</style>